BASEDIR = ../..
CC = gcc
LEXER = re2c
PARSER = $(BASEDIR)/bin/lemon
LEMON_SRC_DIR = $(BASEDIR)/ext/sqlite/tool

INCLUDE_DIR = $(BASEDIR)/include
CODEC_INCLUDE_DIR = $(INCLUDE_DIR)/codec

CODEC_SRC ::= $(wildcard codec_*.c)
PARSER_SRC ::= $(CODEC_SRC:codec_%=parser_%)
CODEC_OBJ ::= $(CODEC_SRC:.c=.o)
PARSER_OBJ ::= $(CODEC_OBJ:codec_%=parser_%)
GRAMMAR_OBJ ::= $(CODEC_OBJ:codec_%=grammar_%)
OBJ = $(GRAMMAR_OBJ) $(PARSER_OBJ) $(CODEC_OBJ)
DBG_OBJ = $(OBJ:%.o=%_dbg.o)

INCLUDE ::= -I$(INCLUDE_DIR) -I../../ext/openldap/libraries/liblmdb \
	-I../../ext/xxHash -I../../ext/tpl/src -I../../ext/hashmap \
	-I../../ext/log/src
CFLAGS = -Wall -fPIC -MMD -DLOG_USE_COLOR $(INCLUDE)
DBG_CFLAGS = -I../../test -O0 -g3 -DDEBUG

.DEFAULT_GOAL := all

.PHONY: codec
codec: $(OBJ)

.PHONY: debug
debug: $(DBG_OBJ)

.PHONY: parsers
parsers: $(PARSER_SRC)

%_dbg.o: %.c
	$(CC) $(CFLAGS) $(DBG_CFLAGS) -c $^ -o $@

# Parser C sources.
parser_%.c: lexer_%.re grammar_%.c ../codec.c
	$(LEXER) $< -o $@ -T --case-ranges


.PRECIOUS: grammar_%.c $(CODEC_INCLUDE_DIR)/tokens_%.h
# Parser generators.
grammar_%.c $(CODEC_INCLUDE_DIR)/tokens_%.h: grammar_%.y
	$(PARSER) $< -p -T$(LEMON_SRC_DIR)/lempar.c -d.
	mv grammar_$*.h $(CODEC_INCLUDE_DIR)/tokens_$*.h
